import React from "react";
import { useState, useEffect } from "react";
import { getInterviewTitleAsync } from "@/redux/interviewSlice";
import { useDispatch, useSelector } from "react-redux";
import { getTypeList } from "@/redux/typeSlice";
import styles from "./Interviews.module.css";
import { PageHeader } from "@/components";
import { Tree } from "antd";
import { getInterviewById } from "@/api/interview";
export default function Interviews() {
  const dispatch = useDispatch();
  const { typeList } = useSelector((state) => state.type);
  const { interviewList } = useSelector((state) => state.interview);
  const [treeData, setTreeData] = useState([]);
  const [interviewInfo, setInterviewInfo] = useState(null);

  const handleTreeClick = (interviewId) => {
    (async () => {
      const res = await getInterviewById(interviewId);
      setInterviewInfo(res.data);
    })();
  };

  useEffect(() => {
    if (!typeList.length) {
      dispatch(getTypeList());
    }
    if (!interviewList.length) {
      dispatch(getInterviewTitleAsync());
    }

    // 获得标题
    let titleArr = typeList.map((type, index) => {
      return {
        title: <h3 style={{ fontWeight: 200, margin: "5px" }}>{type.typeName}</h3>,
        key: index + 1,
        children: [],
      };
    });

    // 获得内容
    for (let i = 0; i < interviewList.length; i++) {
      const childrenArr = [];
      for (let j = 0; j < interviewList[i].length; j++) {
        childrenArr.push({
          title: (
            <h4
              style={{ fontWeight: 200, margin: "5px", padding: "5px 0", width: "180px" }}
              onClick={() => handleTreeClick(interviewList[i][j]._id)}
            >
              {interviewList[i][j].interviewTitle}
            </h4>
          ),
          key: `${i}-${j}`,
        });
      }
      titleArr[i].children = childrenArr;
    }

    setTreeData(titleArr);
  }, [typeList, interviewList]);

  let interviewContent = null;
  if (interviewInfo) {
    interviewContent = (
      <div className={styles.content}>
        <h1 className={styles.interviewRightTitle}>{interviewInfo?.interviewTitle}</h1>
        <div className={styles.contentContainer}>
          <div dangerouslySetInnerHTML={{ __html: interviewInfo?.interviewContent }}></div>
        </div>
      </div>
    );
  } else {
    interviewContent = (
      <div
        style={{
          textAlign: "center",
          fontSize: "30px",
          fontWeight: "100",
          marginTop: "150px",
        }}
      >
        请在左侧选择面试题
      </div>
    );
  }

  return (
    <>
      <div className={styles.container}>
        <PageHeader title={"面试题大全"} />
        <div className={styles.interviewContainer}>
          <div className={styles.LeftSide}>
            <Tree treeData={treeData} />
          </div>
          <div className={styles.rightSide}>{interviewContent}</div>
        </div>
      </div>
    </>
  );
}
